// 导入React的useState、useEffect、useRef、useCallback钩子
import { useState, useEffect, useRef, useCallback } from 'react';
// 导入React Router的useNavigate钩子，用于页面导航
import { useNavigate } from 'react-router-dom';
// 导入Antd Mobile的通知栏组件
import { NoticeBar } from 'antd-mobile';
// 导入Redux hooks
import { useDispatch, useSelector } from 'react-redux';
import type { AppDispatch, RootState } from '../store';
// 导入医生相关的actions

import { fetchDoctorDetail, setCurrentDoctor } from '../store/doctorDetailSlice';
// 导入自定义的API请求工具
import request from '../api/request';
// 导入搜索栏组件
import SearchBar from '../components/SearchBar';
// 导入服务区域组件
import ServicesSection from '../components/ServicesSection';
// 导入模拟数据中的服务和公告数据
import { services, announcements, doctors } from '../data/mockData';

// 定义医生接口类型
interface Doctor {
  id: string; // 医生ID
  name: string; // 医生姓名
  title: string; // 医生职称
  hospital: string; // 所属医院
  department: string; // 科室
  avatar: string; // 头像
  isOnline: boolean; // 是否在线
  consultationMethods: string[]; // 咨询方式
  specialties: string; // 专长
  rating: number; // 评分
  commendations: number; // 推荐数
  views: number; // 浏览量
  price: number; // 价格
  isGradeA?: boolean; // 是否为A级医生
  city?: string; // 城市
  hospitalLevel?: string; // 医院等级
  hospitalType?: string; // 医院类型
  hospitalId?: string; // 医院ID
  doctorIdDoc?: string; // 医生文档ID
  doctorTime?: string; // 医生时间
  socoDesc?: string; // 社交描述
  socoCity?: string; // 社交城市
  socoImage?: string; // 社交图片
}

// 定义科室接口类型
interface Department {
  id: string; // 科室ID
  name: string; // 科室名称
  isActive: boolean; // 是否激活
}

// 定义搜索结果接口类型
interface SearchResult {
  id: string; // 结果ID
  name: string; // 结果名称
  type: 'doctor' | 'hospital' | 'medicine' | 'symptom'; // 结果类型
  description?: string; // 结果描述
}

/**
 * 首页组件 - 妙手医生应用的主页面
 * 
 * 功能特性：
 * - 医生列表展示和筛选
 * - 科室分类切换
 * - 搜索功能集成
 * - 分页加载
 * - 医生详情跳转
 * - Redux状态管理集成
 * 
 * 主要状态：
 * - doctors: 当前显示的医生列表
 * - currentDepartments: 当前科室列表
 * - loading: 页面加载状态
 * - searchResults: 搜索结果
 * - 分页相关状态
 * 
 * @returns {JSX.Element} 首页组件
 */
export default function HomePage() {
  // 获取导航函数，用于页面跳转
  const navigate = useNavigate();
  // 获取Redux dispatch和state
  const dispatch = useDispatch<AppDispatch>();
  const { currentDoctor, loading: doctorDetailLoading, error: doctorError } = useSelector((state: RootState) => state.doctorDetail);
  
  // 定义医生列表状态
  const [doctors, setDoctors] = useState<Doctor[]>([]);
  // 定义当前科室列表状态
  const [currentDepartments, setCurrentDepartments] = useState<Department[]>([]);
  // 定义加载状态
  const [loading, setLoading] = useState(true);
  // 定义错误状态
  const [error, setError] = useState<string | null>(null);
  
  // 分页相关状态
  const [currentPage, setCurrentPage] = useState(1); // 当前页码
  const [pageSize] = useState(2); // 每页显示2条数据，用于测试上拉加载
  const [hasMore, setHasMore] = useState(true); // 是否还有更多数据
  const [loadingMore, setLoadingMore] = useState(false); // 是否正在加载更多
  const [totalDoctors, setTotalDoctors] = useState<Doctor[]>([]); // 所有医生数据
  
  // 搜索相关状态
  const [searchResults, setSearchResults] = useState<SearchResult[]>([]); // 搜索结果
  const [isSearching, setIsSearching] = useState(false); // 是否正在搜索
  const [hasSearchResults, setHasSearchResults] = useState(false); // 是否有搜索结果
  
  // 滚动容器引用
  const scrollContainerRef = useRef<HTMLDivElement>(null);

  // 处理搜索结果
  const handleSearchResults = (results: SearchResult[]) => {
    // 设置搜索结果
    setSearchResults(results);
    // 设置是否有搜索结果
    setHasSearchResults(results.length > 0);
    
    // 如果有搜索结果，过滤医生列表
    if (results.length > 0) {
      // 过滤出医生类型的结果
      const doctorResults = results.filter(result => result.type === 'doctor');
      if (doctorResults.length > 0) {
        // 根据搜索结果过滤医生列表
        const filteredDoctors = totalDoctors.filter(doctor => 
          doctorResults.some(searchResult => 
            doctor.name.includes(searchResult.name) || 
            doctor.department.includes(searchResult.name) ||
            doctor.specialties.includes(searchResult.name)
          )
        );
        // 设置过滤后的医生列表
        setDoctors(filteredDoctors);
        // 搜索结果不需要分页加载
        setHasMore(false);
      }
    } else {
      // 没有搜索结果时，恢复原来的医生列表
      setDoctors(totalDoctors);
      // 设置是否还有更多数据
      setHasMore(totalDoctors.length >= pageSize);
    }
  };

  // 处理搜索加载状态
  const handleSearchLoading = (loading: boolean) => {
    // 设置搜索加载状态
    setIsSearching(loading);
  };

  // 通用的科室匹配函数
  const matchDepartment = (doctorDept: string, selectedDept: string): boolean => {
    // 如果任一科室为空，返回false
    if (!doctorDept || !selectedDept) return false;
    
    // 转换为小写并去除空格
    const doctorDeptLower = doctorDept.toLowerCase().trim();
    const selectedDeptLower = selectedDept.toLowerCase().trim();
    
    // 精确匹配
    if (doctorDeptLower === selectedDeptLower) {
      return true;
    }
    
    // 包含匹配（更精准）
    if (selectedDeptLower.includes('科') && doctorDeptLower.includes(selectedDeptLower.replace('科', ''))) {
      return true;
    }
    
    if (doctorDeptLower.includes('科') && selectedDeptLower.includes(doctorDeptLower.replace('科', ''))) {
      return true;
    }
    
    // 特殊匹配规则
    const specialMatches: Record<string, string[]> = {
      '内科': ['内科', '消化内科', '呼吸内科', '心血管内科', '神经内科', '肾内科', '内分泌科', '血液科', '风湿免疫科', '感染科'],
      '外科': ['外科', '普外科', '骨科', '神经外科', '胸外科', '泌尿外科', '整形外科', '烧伤科'],
      '妇产科': ['妇产科', '妇科', '产科', '生殖科'],
      '儿科': ['儿科', '小儿科', '儿童科'],
      '眼科': ['眼科', '眼科学'],
      '口腔科': ['口腔科', '牙科', '口腔医学'],
      '皮肤科': ['皮肤科', '皮肤病科', '皮肤性病科'],
      '耳鼻喉科': ['耳鼻喉科', '耳鼻咽喉科', '五官科'],
      '精神科': ['精神科', '精神病科', '心理科'],
      '康复科': ['康复科', '康复医学'],
      '中医科': ['中医科', '中医内科', '中医外科', '中医妇科', '中医儿科'],
      '中西医结合科': ['中西医结合科', '中西医结合'],
      '医学影像科': ['医学影像科', '放射科', '影像科', '超声科', '核医学科'],
      '检验科': ['检验科', '临床检验科', '医学检验科'],
      '病理科': ['病理科', '病理学'],
      '药剂科': ['药剂科', '药房', '临床药学'],
      '急诊科': ['急诊科', '急救科', '急症科'],
      '重症医学科': ['重症医学科', 'ICU', '重症监护'],
      '麻醉科': ['麻醉科', '麻醉学'],
      '营养科': ['营养科', '临床营养科'],
      '预防保健科': ['预防保健科', '预防科', '保健科']
    };
    
    // 检查特殊匹配
    for (const [category, aliases] of Object.entries(specialMatches)) {
      if (category === selectedDeptLower || aliases.some(alias => alias === selectedDeptLower)) {
        return aliases.some(alias => doctorDeptLower.includes(alias.replace('科', '')) || doctorDeptLower === alias);
      }
    }
    
    // 模糊匹配（最后的选择）
    const words = selectedDeptLower.split(/[科\s]+/).filter(word => word.length > 0);
    return words.some(word => doctorDeptLower.includes(word));
  };

  // 获取科室数据
  const fetchDepartments = async () => {
    try {
      // 调用API获取科室列表
      const response = await request.get('/office/list');
      
      // 检查响应数据是否有效
      if (response.data && response.data.data && Array.isArray(response.data.data)) {
        // 创建唯一科室的Map
        const uniqueDepartments = new Map<string, { id: string; name: string; isActive: boolean }>();
        
        // 遍历响应数据，提取科室名称
        response.data.data.forEach((item: Record<string, unknown>) => {
          const adminName = item.adminname as string;
          if (adminName && !uniqueDepartments.has(adminName)) {
            // 为每个唯一科室设置ID和状态
            uniqueDepartments.set(adminName, {
              id: String(uniqueDepartments.size + 1),
              name: adminName,
              isActive: uniqueDepartments.size === 0
            });
          }
        });
        
        // 构建完整的科室列表，包含"全部科室"选项
        const allDepartments = [
          { id: '0', name: '全部科室', isActive: true },
          ...Array.from(uniqueDepartments.values()).map(dept => ({
            ...dept,
            isActive: false
          }))
        ];
        
        // 设置科室列表状态
        setCurrentDepartments(allDepartments);
      } else {
        // 如果API调用失败，使用默认科室列表
        const defaultDepartments = [
          { id: '0', name: '全部科室', isActive: true },
          { id: '1', name: '内科', isActive: false },
          { id: '2', name: '外科', isActive: false },
          { id: '3', name: '妇产科', isActive: false },
          { id: '4', name: '儿科', isActive: false },
          { id: '5', name: '眼科', isActive: false },
          { id: '6', name: '口腔科', isActive: false },
          { id: '7', name: '肿瘤科', isActive: false },
          { id: '8', name: '皮肤科', isActive: false },
          { id: '9', name: '中医科', isActive: false },
          { id: '10', name: '中西医结合科', isActive: false },
          { id: '11', name: '医学影像科', isActive: false },
          { id: '12', name: '全科', isActive: false },
          { id: '13', name: '预防保健科', isActive: false },
          { id: '14', name: '急诊科', isActive: false },
          { id: '15', name: '重症医学科', isActive: false },
          { id: '16', name: '麻醉科', isActive: false },
          { id: '17', name: '病理科', isActive: false },
          { id: '18', name: '检验科', isActive: false },
          { id: '19', name: '药剂科', isActive: false },
          { id: '20', name: '康复科', isActive: false },
          { id: '21', name: '营养科', isActive: false },
          { id: '22', name: '心理科', isActive: false },
          { id: '23', name: '感染科', isActive: false },
          { id: '24', name: '血液科', isActive: false },
          { id: '25', name: '风湿免疫科', isActive: false },
          { id: '26', name: '内分泌科', isActive: false },
          { id: '27', name: '消化内科', isActive: false },
          { id: '28', name: '呼吸内科', isActive: false },
          { id: '29', name: '心血管内科', isActive: false },
          { id: '30', name: '神经内科', isActive: false },
          { id: '31', name: '肾内科', isActive: false },
          { id: '32', name: '普外科', isActive: false },
          { id: '33', name: '骨科', isActive: false },
          { id: '34', name: '神经外科', isActive: false },
          { id: '35', name: '胸外科', isActive: false },
          { id: '36', name: '泌尿外科', isActive: false },
          { id: '37', name: '整形外科', isActive: false },
          { id: '38', name: '烧伤科', isActive: false },
          { id: '39', name: '耳鼻喉科', isActive: false },
          { id: '40', name: '精神科', isActive: false }
        ];
        // 设置默认科室列表
        setCurrentDepartments(defaultDepartments);
      }
    } catch (error) {
      // 如果API请求失败，使用默认科室列表
      const defaultDepartments = [
        { id: '0', name: '全部科室', isActive: true },
        { id: '1', name: '内科', isActive: false },
        { id: '2', name: '外科', isActive: false },
        { id: '3', name: '妇产科', isActive: false },
        { id: '4', name: '儿科', isActive: false },
        { id: '5', name: '眼科', isActive: false },
        { id: '6', name: '口腔科', isActive: false },
        { id: '7', name: '肿瘤科', isActive: false },
        { id: '8', name: '皮肤科', isActive: false },
        { id: '9', name: '中医科', isActive: false },
        { id: '10', name: '中西医结合科', isActive: false },
        { id: '11', name: '医学影像科', isActive: false },
        { id: '12', name: '全科', isActive: false },
        { id: '13', name: '预防保健科', isActive: false },
        { id: '14', name: '急诊科', isActive: false },
        { id: '15', name: '重症医学科', isActive: false },
        { id: '16', name: '麻醉科', isActive: false },
        { id: '17', name: '病理科', isActive: false },
        { id: '18', name: '检验科', isActive: false },
        { id: '19', name: '药剂科', isActive: false },
        { id: '20', name: '康复科', isActive: false },
        { id: '21', name: '营养科', isActive: false },
        { id: '22', name: '心理科', isActive: false },
        { id: '23', name: '感染科', isActive: false },
        { id: '24', name: '血液科', isActive: false },
        { id: '25', name: '风湿免疫科', isActive: false },
        { id: '26', name: '内分泌科', isActive: false },
        { id: '27', name: '消化内科', isActive: false },
        { id: '28', name: '呼吸内科', isActive: false },
        { id: '29', name: '心血管内科', isActive: false },
        { id: '30', name: '神经内科', isActive: false },
        { id: '31', name: '肾内科', isActive: false },
        { id: '32', name: '普外科', isActive: false },
        { id: '33', name: '骨科', isActive: false },
        { id: '34', name: '神经外科', isActive: false },
        { id: '35', name: '胸外科', isActive: false },
        { id: '36', name: '泌尿外科', isActive: false },
        { id: '37', name: '整形外科', isActive: false },
        { id: '38', name: '烧伤科', isActive: false },
        { id: '39', name: '耳鼻喉科', isActive: false },
        { id: '40', name: '精神科', isActive: false }
      ];
      // 设置默认科室列表
      setCurrentDepartments(defaultDepartments);
    }
  };

  // 科室切换处理函数
  const handleDepartmentChange = (departmentId: string) => {
    // 更新科室列表，设置选中的科室为激活状态
    const updatedDepartments = currentDepartments.map(dept => ({
      ...dept,
      isActive: dept.id === departmentId
    }));
    // 设置更新后的科室列表
    setCurrentDepartments(updatedDepartments);

    // 找到选中的科室
    const selectedDepartment = updatedDepartments.find(dept => dept.id === departmentId);
    
    // 清除搜索状态
    setHasSearchResults(false);
    setSearchResults([]);
    
    if (selectedDepartment && selectedDepartment.name === '全部科室') {
      // 显示所有医生，重新启用分页加载
      setDoctors(totalDoctors);
      setHasMore(totalDoctors.length >= pageSize);
      setCurrentPage(1); // 重置页码
    } else if (selectedDepartment) {
      // 使用更精准的科室匹配逻辑过滤医生
      const filteredDoctors = totalDoctors.filter(doctor => {
        if (!doctor.department) return false;
        return matchDepartment(doctor.department, selectedDepartment.name);
      });
      
      // 只显示第一页的数据
      const firstPageDoctors = filteredDoctors.slice(0, pageSize);
      setDoctors(firstPageDoctors);
      
      // 如果过滤后的数据多于pageSize，说明还有更多数据
      setHasMore(filteredDoctors.length > pageSize);
      setCurrentPage(1); // 重置页码
    }
  };

  // 获取医生数据 - 支持分页
  const fetchDoctors = async (page: number = 1, append: boolean = false) => {
    try {
      if (page === 1) {
        // 第一页时设置主加载状态
        setLoading(true);
      } else {
        // 其他页时设置加载更多状态
        setLoadingMore(true);
      }
      // 清空错误信息
      setError(null);
      
      // 构建请求参数
      const params: Record<string, string> = {
        pageCode: page.toString(),
        pageSize: pageSize.toString()
      };

      // 调用API获取医生列表
      const response = await request.get('/doctor/list', { params });
      
      // 检查响应数据并转换为标准格式
      if (response.data && response.data.data && Array.isArray(response.data.data)) {
        // 将API返回的数据映射为标准的医生对象格式
        const apiDoctors = response.data.data.map((item: Record<string, unknown>, index: number) => ({
          id: item.doctorid || item.id || `doctor_${page}_${index}_${Date.now()}`,
          name: item.doctorname || item.name || '未知医生',
          title: item.doctorstate || item.title || '医生',
          hospital: item.nosocomium || item.hospital || '未知医院',
          department: item.socoadmin || item.doctoradministre || item.department || '未知科室',
          avatar: (item.doctorimage || item.avatar) || null,
          isOnline: item.doctorstate === '在线' || item.isOnline !== undefined ? item.isOnline : Math.random() > 0.5,
          consultationMethods: Array.isArray(item.consultationMethods) 
            ? item.consultationMethods 
            : ['图文咨询'],
          specialties: item.doctordescword || item.specialties || item.specialty || '专业医疗',
          rating: item.doctorgood || item.rating || item.score || Math.floor(Math.random() * 20) + 80,
          commendations: item.doctorflag ? item.doctorflag.toString().split(',').length : Math.floor(Math.random() * 10),
          views: item.doctorbrowse || item.views || item.viewCount || Math.floor(Math.random() * 10000) + 5000,
          price: item.doctorprice || item.price || item.consultationPrice || Math.floor(Math.random() * 50) + 10,
          isGradeA: item.socolv === '公立' || item.isGradeA || item.grade === 'A' || Math.random() > 0.7,
          city: item.doctorcity || item.city || '',
          hospitalLevel: item.socolv || '',
          hospitalType: item.socostate || '',
          hospitalId: item.socoid || '',
          doctorIdDoc: item.doctoriddoc || '',
          doctorTime: item.doctortime || '',
          socoDesc: item.socodescword || '',
          socoCity: item.sococity || '',
          socoImage: item.socoimage || ''
        }));
        
        if (append) {
          // 上拉加载时，需要去重，只添加新的医生数据
          const existingIds = new Set(doctors.map((doctor: Doctor) => doctor.id));
          const newDoctors = apiDoctors.filter((doctor: Doctor) => !existingIds.has(doctor.id));
          
          if (newDoctors.length > 0) {
            setTotalDoctors(prev => [...prev, ...newDoctors]);
            setDoctors(prev => [...prev, ...newDoctors]);
          } else {
            // 上拉加载没有新数据，所有医生都已存在
          }
          
          // 判断是否还有更多数据 - 如果返回的数据少于pageSize，说明没有更多数据了
          setHasMore(apiDoctors.length === pageSize);
        } else {
          // 首次加载或刷新时，直接替换数据
          setTotalDoctors(apiDoctors);
          setDoctors(apiDoctors);
          setHasMore(apiDoctors.length === pageSize);
        }
        
        // 打印医生数据总数到控制台
        // console.log('医生数据总数:', apiDoctors.length);
        // console.log('医生数据详情:', apiDoctors);
        // console.log('API响应原始数据:', response.data);
        // console.log('当前页面大小:', pageSize);
        // console.log('是否追加模式:', append);
        
        // 专门检查头像字段
        // console.log('前5个医生的头像字段:');
        // apiDoctors.slice(0, 5).forEach((doctor: Doctor, index: number) => {
        //   console.log(`医生${index + 1} (${doctor.name}):`);
        //   console.log(`  - avatar = "${doctor.avatar}"`);
        //   console.log(`  - avatar type = ${typeof doctor.avatar}`);
        //   console.log(`  - avatar length = ${doctor.avatar ? doctor.avatar.length : 0}`);
        //   console.log(`  - has avatar = ${doctor.avatar ? 'true' : 'false'}`);
        // });
        
        // 检查原始API数据中的头像字段
        // console.log('原始API数据中的头像字段:');
        // response.data.data.slice(0, 5).forEach((item: any, index: number) => {
        //   console.log(`原始数据${index + 1}:`);
        //   console.log(`  - doctorimage = "${item.doctorimage}"`);
        //   console.log(`  - avatar = "${item.avatar}"`);
        //   console.log(`  - 最终映射结果 = "${(item.doctorimage || item.avatar) || null}"`);
          
        //   // 测试头像URL是否有效
        //   const avatarUrl = item.doctorimage || item.avatar;
        //   if (avatarUrl) {
        //     console.log(`  - 头像URL: ${avatarUrl}`);
        //     // 尝试创建一个Image对象来测试URL
        //     const img = new Image();
        //     img.onload = () => console.log(`  - 头像URL有效，尺寸: ${img.width}x${img.height}`);
        //     img.onerror = () => console.log(`  - 头像URL无效或无法加载`);
        //     img.src = avatarUrl;
            
        //     // 在控制台直接显示测试图片
        //     console.log(`  - 测试图片:`);
        //     console.log(`%c`, `background-image: url(${avatarUrl}); background-size: 50px 50px; padding: 25px; border-radius: 25px;`);
        //   }
        // });
        
        setCurrentPage(page);
      } else {
        // 如果API没有返回数据，设置空数组
        if (append) {
          // 上拉加载时，如果没有新数据，标记没有更多
          setHasMore(false);
        } else {
          setDoctors([]);
          setTotalDoctors([]);
          setHasMore(false);
        }
      }
    } catch (err) {
      setError('获取医生数据失败，请稍后重试');
      
      // 错误时不显示任何数据，保持当前状态
      if (!append) {
        setDoctors([]);
        setTotalDoctors([]);
      }
      setHasMore(false);
    } finally {
      setLoading(false);
      setLoadingMore(false);
    }
  };

  // 加载更多数据
  const loadMore = useCallback(async () => {
    if (loadingMore || !hasMore) return;
    
    // 检查当前是否在科室过滤状态
    const activeDepartment = currentDepartments.find(dept => dept.isActive);
    const isFiltered = activeDepartment && activeDepartment.name !== '全部科室';
    
    if (isFiltered) {
      // 如果是科室过滤状态，从已加载的数据中查找更多
      const currentDoctors = doctors;
      
      // 使用相同的精准过滤逻辑
      const allFilteredDoctors = totalDoctors.filter((doctor: Doctor) => {
        if (!doctor.department) return false;
        return matchDepartment(doctor.department, activeDepartment.name);
      });
      
      // 计算当前显示的数量和剩余数量
      const currentCount = currentDoctors.length;
      const totalFilteredCount = allFilteredDoctors.length;
      
      if (currentCount < totalFilteredCount) {
        // 还有更多过滤后的数据可以显示
        const nextBatch = allFilteredDoctors.slice(currentCount, currentCount + pageSize);
        
        // 去重，确保不添加重复的医生
        const existingIds = new Set(currentDoctors.map((doctor: Doctor) => doctor.id));
        const newDoctors = nextBatch.filter((doctor: Doctor) => !existingIds.has(doctor.id));
        
        if (newDoctors.length > 0) {
          setDoctors(prev => [...prev, ...newDoctors]);
          setHasMore(currentCount + newDoctors.length < totalFilteredCount);
        } else {
          setHasMore(false);
        }
      } else {
        setHasMore(false);
      }
    } else {
      // 如果是全部科室状态，正常加载下一页
      const nextPage = currentPage + 1;
      await fetchDoctors(nextPage, true);
    }
  }, [currentPage, hasMore, loadingMore, currentDepartments, doctors, totalDoctors, pageSize]);

  // 滚动监听 - 检测是否接近底部
  const handleScroll = useCallback(() => {
    if (!scrollContainerRef.current || loadingMore || !hasMore) return;
    
    const container = scrollContainerRef.current;
    const scrollTop = container.scrollTop;
    const scrollHeight = container.scrollHeight;
    const clientHeight = container.clientHeight;
    
    // 当距离底部100px时触发加载更多
    if (scrollHeight - scrollTop - clientHeight < 100) {
      // 添加防抖，避免快速滚动时多次触发
      if (!loadingMore) {
        loadMore()
      }
    }
  }, [loadMore, loadingMore, hasMore]);

  // 添加滚动监听，使用节流优化性能
  useEffect(() => {
    const container = scrollContainerRef.current;
    if (container) {
      let timeoutId: number;
      
      const throttledHandleScroll = () => {
        if (timeoutId) {
          clearTimeout(timeoutId);
        }
        timeoutId = setTimeout(handleScroll, 100); // 100ms 防抖
      };
      
      container.addEventListener('scroll', throttledHandleScroll);
      return () => {
        container.removeEventListener('scroll', throttledHandleScroll);
        if (timeoutId) {
          clearTimeout(timeoutId);
        }
      };
    }
  }, [handleScroll]);

  // 初始加载医生数据
  useEffect(() => {
    const initializeData = async () => {
      await fetchDepartments();
      await fetchDoctors(1, false);
    };
    initializeData();
  }, []);

  const handleConsult = (doctorId: string) => {
    // 跳转到在线咨询页面
            navigate(`/online-consultation`);
  };



  const handleDoctorClick = async (doctorId: string) => {
    console.log('点击医生卡片，doctorId:', doctorId);
    console.log('当前显示的医生数据总数:', doctors.length);
    console.log('当前显示的医生ID列表:', doctors.map(d => d.id));
    
    // 在当前显示的医生列表中查找
    const targetDoctor = doctors.find(d => d.id === doctorId);
    
    if (targetDoctor) {
      console.log('找到医生数据:', targetDoctor);
      // 直接设置当前医生
      dispatch(setCurrentDoctor(targetDoctor));
      
      const navigationState = {
        doctorName: targetDoctor.name,
        doctorDescription: targetDoctor.specialties || ''
      };
      console.log('准备跳转，状态:', navigationState);
      
      navigate(`/doctor/${doctorId}`, {
        state: navigationState
      });
    } else {
      console.log('未找到医生数据，直接跳转');
      // 如果没有数据，直接跳转
      navigate(`/doctor/${doctorId}`);
    }
    
    // 异步获取医生详情（不阻塞跳转）
    try {
      const result = await dispatch(fetchDoctorDetail(doctorId)).unwrap();
      if (result) {
        console.log('成功获取医生详情:', result);
        dispatch(setCurrentDoctor(result));
      }
    } catch (error) {
      console.error('获取医生详情失败:', error);
    }
  };

  return (
    <div className="min-h-screen bg-gray-50">
      {/* 搜索栏 */}
      <SearchBar 
        onSearchResults={handleSearchResults}
        onSearchLoading={handleSearchLoading}
      />
      
      {/* 公告栏 */}
      <div className="mobile-px mobile-py">
        {announcements.map((announcement) => (
          <div key={announcement.id} className="mb-3">
            <NoticeBar
              content={announcement.content}
              color={announcement.type === 'warning' ? 'alert' : announcement.type === 'success' ? 'success' : 'default'}
              closeable
            />
          </div>
        ))}
      </div>
      
      {/* 服务区域 */}
      <div className="mb-6">
        <ServicesSection services={services} />
      </div>
      
      {/* 我要问专家 */}
      <div className="mobile-px pb-6">
        <div className="mobile-card p-6 mb-4">
          <div className="flex items-center justify-between mb-6">
            <h2 className="text-xl font-bold text-gray-900">我要问专家</h2>
            <button className="text-sm text-primary-600 hover:text-primary-700 font-medium transition-colors touch-feedback">
              更多&gt;
            </button>
          </div>
          
          {/* 科室选择 */}
          <div className="mb-6">
            <div className="flex space-x-3 overflow-x-auto pb-2 scrollbar-hide">
              {currentDepartments.map((department) => (
                <button
                  key={department.id}
                  onClick={() => handleDepartmentChange(department.id)}
                  className={`px-4 py-2.5 rounded-full text-sm font-medium whitespace-nowrap transition-all duration-200 flex-shrink-0 touch-feedback ${
                    department.isActive
                      ? 'bg-primary-500 text-white shadow-lg transform scale-105'
                      : 'bg-gray-100 text-gray-600 hover:bg-gray-200 hover:shadow-md'
                  }`}
                >
                  {department.name}
                </button>
              ))}
            </div>
          </div>

          {/* 搜索状态提示 */}
          {isSearching && (
            <div className="text-center py-4 mb-4">
              <div className="inline-flex items-center space-x-2 text-primary-600">
                <div className="w-4 h-4 border-2 border-primary-500 border-t-transparent rounded-full animate-spin"></div>
                <span>正在搜索...</span>
              </div>
            </div>
          )}

          {/* 搜索结果提示 */}
          {hasSearchResults && !isSearching && (
            <div className="mb-4 p-3 bg-blue-50 border border-blue-200 rounded-lg">
              <div className="flex items-center justify-between">
                <div className="flex items-center space-x-2">
                  <span className="text-blue-600">🔍</span>
                  <span className="text-sm text-blue-800">
                    搜索到 {searchResults.length} 个相关结果
                  </span>
                </div>
                <button
                  onClick={() => {
                    setHasSearchResults(false);
                    setDoctors(totalDoctors);
                    setHasMore(totalDoctors.length >= pageSize);
                  }}
                  className="text-xs text-blue-600 hover:text-blue-800 underline"
                >
                  清除搜索
                </button>
              </div>
            </div>
          )}

          {/* 专家列表 - 添加滚动容器 */}
          <div 
            ref={scrollContainerRef}
            className="max-h-80 overflow-y-auto scrollbar-hide"
          >
            {loading ? (
              <div className="space-y-4">
                {[1, 2].map((index) => (
                  <div key={index} className="mobile-card p-4 border border-gray-100 animate-pulse">
                    <div className="flex items-start space-x-4">
                      <div className="w-16 h-16 bg-gray-200 rounded-full flex-shrink-0"></div>
                      <div className="flex-1 space-y-3">
                        <div className="h-4 bg-gray-200 rounded w-3/4"></div>
                        <div className="h-3 bg-gray-200 rounded w-1/2"></div>
                        <div className="h-3 bg-gray-200 rounded w-2/3"></div>
                        <div className="h-3 bg-gray-200 rounded w-1/3"></div>
                      </div>
                    </div>
                  </div>
                ))}
              </div>
            ) : error ? (
              <div className="text-center py-8">
                <div className="text-red-500 text-6xl mb-4">⚠️</div>
                <p className="text-gray-600 mb-4">{error}</p>
                <button 
                  onClick={() => fetchDoctors(1, false)}
                  className="mobile-btn mobile-btn-primary"
                >
                  重新加载
                </button>
              </div>
            ) : (
              <>
                {/* 医生列表 */}
                <div className="space-y-4">
                  {doctors.map((doctor) => (
                    <div
                      key={doctor.id}
                      className="mobile-card p-4 border border-gray-100 hover:shadow-md transition-all duration-200 cursor-pointer touch-feedback"
                      onClick={() => handleDoctorClick(doctor.id)}
                    >
                      <div className="flex items-start space-x-4">
                        {/* 专家头像 */}
                        <div className="relative flex-shrink-0">
                          {/* 如果有头像，显示图片 */}
                          {doctor.avatar ? (
                            <img 
                              src={doctor.avatar} 
                              alt={`${doctor.name}的头像`}
                              className="w-16 h-16 rounded-full object-cover shadow-md"
                              onError={(e) => {
                                console.error('头像加载失败:', doctor.avatar, e);
                                // 如果头像加载失败，隐藏图片，显示文字头像
                                const target = e.target as HTMLImageElement;
                                target.style.display = 'none';
                                const textAvatar = target.nextElementSibling as HTMLElement;
                                if (textAvatar) {
                                  textAvatar.style.display = 'flex';
                                }
                              }}
                              onLoad={(e) => {
                                // console.log('头像加载成功:', doctor.avatar);
                                // 头像加载成功后，隐藏文字头像
                                const target = e.target as HTMLImageElement;
                                const textAvatar = target.nextElementSibling as HTMLElement;
                                if (textAvatar) {
                                  textAvatar.style.display = 'none';
                                }
                              }}
                            />
                          ) : null}
                          
                          {/* 文字头像 - 当没有头像或头像加载失败时显示 */}
                          <div 
                            className="w-16 h-16 rounded-full bg-gradient-to-br from-primary-400 to-primary-600 flex items-center justify-center shadow-md"
                            style={{ 
                              display: doctor.avatar ? 'none' : 'flex'
                            }}
                          >
                            <span className="text-lg font-semibold text-white">
                              {doctor.name ? doctor.name.charAt(0) : '医'}
                            </span>
                          </div>
                          
                          {doctor.isOnline && (
                            <div className="absolute -bottom-1 -right-1">
                              <div className="w-4 h-4 bg-green-500 rounded-full border-2 border-white shadow-sm"></div>
                            </div>
                          )}
                        </div>

                        {/* 专家信息 */}
                        <div className="flex-1 min-w-0">
                          <div className="flex items-center space-x-2 mb-2">
                            <h3 className="text-base font-semibold text-gray-900 truncate">
                              {doctor.name || '未知医生'} {doctor.title || '医生'}
                            </h3>
                            {doctor.isGradeA && (
                              <span className="px-2 py-0.5 bg-green-100 text-green-700 text-xs rounded-full font-medium flex-shrink-0">
                                三甲
                              </span>
                            )}
                          </div>
                          
                          <p className="text-sm text-gray-600 mb-2 truncate">
                            {doctor.hospital || '未知医院'} {doctor.department || '未知科室'}
                          </p>
                          {doctor.city && (
                            <p className="text-xs text-gray-500 mb-2">
                              📍 {doctor.city}
                            </p>
                          )}
                          {doctor.hospitalLevel && (
                            <div className="flex items-center gap-2 mb-2">
                              <span className="px-2 py-0.5 bg-blue-100 text-blue-700 text-xs rounded-full">
                                {doctor.hospitalLevel}
                              </span>
                              {doctor.hospitalType && (
                                <span className="px-2 py-0.5 bg-green-100 text-green-700 text-xs rounded-full">
                                  {doctor.hospitalType}
                                </span>
                              )}
                            </div>
                          )}

                          {/* 咨询方式 */}
                          <div className="flex flex-wrap gap-2 mb-3">
                            {doctor.consultationMethods.map((method) => (
                              <span
                                key={method}
                                className="px-2 py-1 border border-primary-200 text-primary-600 text-xs rounded-full bg-primary-50 font-medium"
                              >
                                {method}
                              </span>
                            ))}
                          </div>

                          {/* 擅长领域 */}
                          <div className="mb-3">
                            <p className="text-sm text-gray-700 line-clamp-2 leading-relaxed">
                              擅长：{doctor.specialties}
                            </p>
                            <button className="text-primary-600 text-xs mt-1 hover:text-primary-700 transition-colors touch-feedback">
                              <svg className="w-3 h-3 inline" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                                <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M19 9l-7 7-7-7" />
                              </svg>
                            </button>
                          </div>

                          {/* 统计信息 */}
                          <div className="flex items-center space-x-4 text-xs text-gray-500 mb-4">
                            <span className="flex items-center gap-1">
                              <span className="w-2 h-2 bg-green-400 rounded-full"></span>
                              好评率{doctor.rating}%
                            </span>
                            <span className="flex items-center gap-1">
                              <span className="w-2 h-2 bg-blue-400 rounded-full"></span>
                              锦旗{doctor.commendations}
                            </span>
                            <span className="flex items-center gap-1">
                              <span className="w-2 h-2 bg-purple-400 rounded-full"></span>
                              浏览{doctor.views}
                            </span>
                            {doctor.doctorTime && (
                              <span className="flex items-center gap-1">
                                <span className="w-2 h-2 bg-orange-400 rounded-full"></span>
                                响应时间{doctor.doctorTime}分钟
                              </span>
                            )}
                          </div>

                          {/* 价格和咨询按钮 */}
                          <div className="flex items-center justify-between">
                            <div className="flex items-baseline gap-1">
                              <span className="text-lg font-bold text-red-500">¥{doctor.price}</span>
                              <span className="text-sm text-gray-500">起</span>
                            </div>
                            <button
                              onClick={(e) => {
                                e.stopPropagation();
                                handleConsult(doctor.id);
                              }}
                              className="mobile-btn mobile-btn-primary touch-feedback"
                            >
                              问医生
                            </button>
                          </div>
                        </div>
                      </div>
                    </div>
                  ))}
                </div>

                {/* 加载更多提示 */}
                {loadingMore && (
                  <div className="text-center py-4">
                    <div className="inline-flex items-center space-x-2 text-gray-500">
                      <div className="w-4 h-4 border-2 border-primary-500 border-t-transparent rounded-full animate-spin"></div>
                      <span>加载中...</span>
                    </div>
                  </div>
                )}

                {/* 没有更多数据提示 */}
                {!loadingMore && !hasMore && doctors.length > 0 && (
                  <div className="text-center py-4">
                    <span className="text-gray-400 text-sm">没有更多数据了</span>
                  </div>
                )}

                {/* 手动加载更多按钮 */}
                {!loadingMore && hasMore && (
                  <div className="text-center py-4">
                    <div className="text-xs text-gray-400 mb-2">
                      当前第{currentPage}页，显示{doctors.length}条数据
                      {(() => {
                        const activeDepartment = currentDepartments.find(dept => dept.isActive);
                        if (activeDepartment && activeDepartment.name !== '全部科室') {
                          const totalFiltered = totalDoctors.filter(doctor => {
                            if (!doctor.department) return false;
                            return matchDepartment(doctor.department, activeDepartment.name);
                          }).length;
                          return `，该科室共${totalFiltered}条`;
                        }
                        return '';
                      })()}
                    </div>
                    <button
                      onClick={loadMore}
                      className="px-6 py-2 bg-gray-100 text-gray-600 rounded-lg text-sm hover:bg-gray-200 transition-colors"
                    >
                      加载更多
                    </button>
                  </div>
                )}
              </>
            )}

            {!loading && !error && doctors.length === 0 && (
              <div className="text-center py-8">
                <p className="text-gray-500">暂无符合条件的专家</p>
                <p className="text-sm text-gray-400 mt-1">请尝试其他筛选条件</p>
              </div>
            )}
          </div>
        </div>
      </div>
    </div>
  );
}